package com.sz.web.common.initialize;

import com.sz.web.account.entity.AccountRole;
import com.sz.web.account.entity.AccountUser;
import com.sz.web.account.entity.AccountUserRole;
import com.sz.web.account.enums.AccountStatus;
import com.sz.web.account.mapper.*;
import com.sz.web.util.Encript;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 账户初始化
 */
@Component
public class AccountInit {
    @Resource
    private AccountUserMapper accountUserMapper;
    @Resource
    private AccountRoleMapper accountRoleMapper;
    @Resource
    private AccountUserRoleMapper accountUserRoleMapper;

    @Value("${web.manager.account}")
    private String managerAccount;
    @Value("${web.manager.password}")
    private String managerPassword;

    private static final Logger logger = LoggerFactory.getLogger(MyApplicationRunner.class);

    /**
     * 管理员初始化
     */
    public void managerInit() {
        int res = accountUserMapper.selectManager();
        int insertUser;
        int insertRole;
        int insertUserRole;
        if (res <= 0) {
            //新增一个管理员用户
            AccountUser accountUser = new AccountUser();
            accountUser.setAccount(managerAccount);
            accountUser.setPassword(Encript.md5(managerPassword));
            accountUser.setEmail("");
            accountUser.setMobilePhone("");
            accountUser.setUsername("管理员");
            insertUser = accountUserMapper.insert(accountUser);
            if (insertUser >= 0) {
                //新增一个管理员角色
                AccountRole accountRole = new AccountRole();
                accountRole.setRoleName("管理员");
                accountRole.setParentId(0);
                accountRole.setStatus(AccountStatus.USING.getStatus());
                insertRole = accountRoleMapper.insert(accountRole);

                if (insertRole >= 0) {
                    //新增用户-角色关联表
                    AccountUserRole accountUserRole = new AccountUserRole();
                    accountUserRole.setUserId(accountUser.getId());
                    accountUserRole.setRoleId(accountRole.getId());
                    insertUserRole = accountUserRoleMapper.insert(accountUserRole);
                    if (insertUserRole>0){
                        logger.info("初始化了一个管理员");
                    }
                }
            }
        }
    }
}
